package com.theobserver.theobserver;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.SaveCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Created by wssxk on 7/8/17.
 */

public class NewsDetailActivity extends Activity {


    RelativeLayout news_content = null;
    RelativeLayout news_loading = null;
    WebView news_webview = null;
    AVObject news = null;
    View custom_content = null;
    //ArrayList<Bitmap> news_images;
    ArrayList<ImageView> news_image_views = null;       //显示图片的imageview
    int image_set_count = 0;
    LinearLayout images_album = null;
    AVUser cur_user = null;


    int is_star = -1;
    int is_like = -1;
    AVObject collect_instance = null;
    AVObject like_instance = null;

    public void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstance);
        setContentView(R.layout.news_detail_layout);

        /*
        WebView wv = (WebView) findViewById(R.id.webview_news_detail);
        WebSettings web_setting = wv.getSettings();
        web_setting.setJavaScriptEnabled(true);
        wv.loadUrl("http://www.baidu.com/");

        wv.setWebViewClient(new WebViewClient()
        {
            public boolean shouldOverrideUrlLoading(WebView webview, String url)
            {
                webview.loadUrl(url);
                return true;
            }
        });*/

        news_content = findViewById(R.id.relativelayout_news_detail_content);
        news_loading = findViewById(R.id.relativelayout_news_detail_loading);

        final ImageView t_webview_back = (ImageView) findViewById(R.id.imageview_news_detail_back);
        final ImageView t_webview_forward = (ImageView) findViewById(R.id.imageview_news_detail_forward);
        t_webview_back.setVisibility(View.GONE);
        t_webview_forward.setVisibility(View.GONE);


        TextView activity_return = (TextView) findViewById(R.id.textview_news_detail_return);
        activity_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        final NewsDetailActivity thisClass = this;
        Intent news_intent = getIntent();
        news = AVObject.createWithoutData("news", (String) news_intent.getCharSequenceExtra("objectId"));
        news.fetchInBackground(new GetCallback<AVObject>() {            //将新闻获取下来
            @Override
            public void done(AVObject avObject, AVException e) {
                if(e != null)
                {
                    Toast.makeText(NewsDetailActivity.this, "读取新闻时发生错误\n" + e.toString(), Toast.LENGTH_SHORT).show();
                }
                else
                {
                    /*
                    news_webview = new WebView(NewsDetailActivity.this);
                    webviewInit(news_webview);
                    news_content.addView(news_webview);
                    news_loading.setVisibility(View.GONE);
                    news_webview.loadUrl(avObject.getString("news_url"));
                    */
                    news = avObject;
                    //newsGot();                    //整合时使用
                    //cur_user = new AVUser();
                    //cur_user.setObjectId("5961b956ac502e005819946c");
                    /*
                    cur_user.fetchInBackground(new GetCallback<AVObject>() {
                        @Override
                        public void done(AVObject avObject, AVException e) {
                            if(e == null)
                            {
                                newsGot();
                            }
                            else
                            {
                                Toast.makeText(NewsDetailActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    */

                    cur_user = AVUser.getCurrentUser();
                    newsGot();





                }
            }
        });

    }


    static public void webviewInit(WebView wv)
    {
        WebSettings web_setting = wv.getSettings();
        web_setting.setJavaScriptEnabled(true);
        //wv.loadUrl("http://www.baidu.com/");


        wv.setWebViewClient(new WebViewClient()
        {
            public boolean shouldOverrideUrlLoading(WebView webview, String url)
            {
                if (url.startsWith("intent")) {
                    //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(httpurl));
                    //startActivity(intent);
                    return false;
                }
                webview.loadUrl(url);
                return true;
            }
        });



        /*
        wv.setWebChromeClient(new WebChromeClient()
        {
            public boolean shouldOverrideUrlLoading(WebView webview, String url)
            {
                webview.loadUrl(url);
                return true;
            }
        });
        */

    }


    public void newsGot()
    {

        final ImageView t_star = (ImageView) findViewById(R.id.imageview_news_detail_star);
        final TextView t_like = (TextView) findViewById(R.id.textview_news_detail_like);
        final ImageView t_webview_back = (ImageView) findViewById(R.id.imageview_news_detail_back);
        final ImageView t_webview_forward = (ImageView) findViewById(R.id.imageview_news_detail_forward);
        //final ImageView t_webview_refresh = (ImageView) findViewById(R.id.imageview_news_detail_webrefresh);
        final TextView t_textview_comment = (TextView) findViewById(R.id.textview_news_detail_comment);
        final ImageView t_imageview_share = (ImageView) findViewById(R.id.imageview_news_detail_share);

        //final

        //cur_user = AVUser.getCurrentUser();                   //整合时使用
        if(cur_user != null)
        {


            //------------------------------------------------------------------
            //新闻收藏相关
            //判断是否已收藏新闻
            AVQuery<AVObject> query_collect = new AVQuery<>("collect");
            query_collect.whereEqualTo("user_email", (AVObject)cur_user);
            query_collect.whereEqualTo("news_id", news);
            query_collect.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException e) {
                    if(e == null && list.size() != 0)
                    {
                        //已收藏
                        //t_star = (ImageView) findViewById(R.id.imageview_news_detail_star);
                        t_star.setImageResource(R.drawable.ic_action_star_red);
                        is_star = 1;
                        collect_instance = list.get(0);
                    }
                    else
                    {
                        //未收藏
                        is_star = 0;
                    }

                    //设置监听
                    t_star.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(is_star == 1)
                            {
                                t_star.setImageResource(R.drawable.ic_action_start_white);
                                collect_instance.deleteInBackground(new DeleteCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if(e == null)
                                        {
                                            Toast.makeText(NewsDetailActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                //collect_instance = null;
                                is_star = 0;
                            }
                            else if(is_star == 0)
                            {

                                AVObject t_collect_instance = new AVObject("collect");
                                t_collect_instance.put("user_email", cur_user);
                                t_collect_instance.put("news_id", news);
                                t_collect_instance.saveInBackground();
                                collect_instance = t_collect_instance;
                                is_star = 1;
                                t_star.setImageResource(R.drawable.ic_action_star_red);
                                Toast.makeText(NewsDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();


                                /*

                                if(collect_instance != null)
                                {
                                    //存在收藏示例
                                    collect_instance.saveInBackground();
                                    t_star.setImageResource(R.drawable.ic_action_star_red);
                                    is_star = 1;
                                }
                                else
                                {
                                    //不存在收藏实例
                                    AVObject t_collect_instance = new AVObject("collect");
                                    t_collect_instance.put("user_email", cur_user);
                                    t_collect_instance.put("news_id", news);
                                    t_collect_instance.saveInBackground();
                                    collect_instance = t_collect_instance;
                                    is_star = 1;
                                    t_star.setImageResource(R.drawable.ic_action_star_red);
                                }
                                */
                            }
                        }
                    });

                }
            });


            //新闻收藏相关
            //------------------------------------------------------------

            //------------------------------------------------------------
            //新闻点赞相关


            t_like.setText(news.getInt("news_like_count")+"");
            AVQuery<AVObject> query_like = new AVQuery<>("like");
            query_like.whereEqualTo("user_email", (AVObject) cur_user);
            query_like.whereEqualTo("news_id", news);
            //查询点赞表
            query_like.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(final List<AVObject> list, AVException e) {
                    if(e != null)
                    {
                        Toast.makeText(NewsDetailActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                    if(e == null && list.size() != 0)
                    {
                        //////////////////////////////////
                        //t_star = (ImageView) findViewById(R.id.imageview_news_detail_star);
                        //t_star.setImageResource(R.drawable.ic_action_star_red);
                        t_like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_action_like_red, 0, 0, 0);
                        is_like = 1;
                        //collect_instance = list.get(0);
                        like_instance = list.get(0);
                        //Toast.makeText(NewsDetailActivity.this, "有赞", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        is_like = 0;
                        //Toast.makeText(NewsDetailActivity.this, "无赞", Toast.LENGTH_SHORT).show();
                    }

                    //设置监听
                    t_like.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(is_like == 1)
                            {
                                //t_like.setImageResource(R.drawable.ic_action_start_white);
                                t_like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_action_like_white, 0, 0, 0);
                                like_instance.deleteInBackground(new DeleteCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if(e != null)
                                        {
                                            Toast.makeText(NewsDetailActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                        {
                                            Toast.makeText(NewsDetailActivity.this, "取消点赞", Toast.LENGTH_SHORT).show();
                                            t_like.setText(news.getInt("news_like_count")-1+"");
                                            news.put("news_like_count", news.getInt("news_like_count")-1);
                                            news.saveInBackground();
                                        }

                                    }
                                });
                                //collect_instance = null;
                                is_like = 0;

                            }
                            else if(is_like == 0)
                            {

                                AVObject t_like_instance = new AVObject("like");
                                t_like_instance.put("user_email", cur_user);
                                t_like_instance.put("news_id", news);
                                t_like_instance.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if(e != null)
                                        {
                                            Toast.makeText(NewsDetailActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                        {
                                            t_like.setText(news.getInt("news_like_count")+1+"");
                                            news.put("news_like_count", news.getInt("news_like_count")+1);
                                            news.saveInBackground();
                                            Toast.makeText(NewsDetailActivity.this, "已点赞", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                like_instance = t_like_instance;
                                is_like = 1;
                                //t_star.setImageResource(R.drawable.ic_action_star_red);
                                t_like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_action_like_red, 0, 0, 0);



                                /*
                                if(like_instance != null)
                                {
                                    //存在收藏示例
                                    like_instance.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(AVException e) {
                                            if(e != null)
                                            {
                                                Toast.makeText(NewsDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                    //t_st.setImageResource(R.drawable.ic_action_star_red);
                                    t_like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_action_like_red, 0, 0, 0);
                                    is_like = 1;
                                }
                                else
                                {
                                    //不存在收藏实例
                                    AVObject t_like_instance = new AVObject("like");
                                    t_like_instance.put("user_email", cur_user);
                                    t_like_instance.put("news_id", news);
                                    t_like_instance.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(AVException e) {
                                            if(e != null)
                                            {
                                                Toast.makeText(NewsDetailActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                    like_instance = t_like_instance;
                                    is_like = 1;
                                    //t_star.setImageResource(R.drawable.ic_action_star_red);
                                    t_like.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_action_like_red, 0, 0, 0);
                                }

                                */

                            }
                        }
                    });

                }
            });






            //新闻点赞相关
            //------------------------------------------------------------






        }
        else        //用户未登录
        {
            t_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(NewsDetailActivity.this, "请先登陆", Toast.LENGTH_SHORT).show();
                }
            });

            t_star.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(NewsDetailActivity.this, "请先登陆", Toast.LENGTH_SHORT).show();
                }
            });

            t_imageview_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(NewsDetailActivity.this, "请先登陆", Toast.LENGTH_SHORT).show();
                }
            });

            /*
            t_textview_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(NewsDetailActivity.this, "请先登陆", Toast.LENGTH_SHORT).show();
                }
            });
            */
        }


        //------------------------------------------------------------
        //用户评论相关

        t_textview_comment.setText(news.getInt("news_comment_count")+"");
        t_textview_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent comment_intent = new Intent(NewsDetailActivity.this, NewsCommentActivity.class);
                comment_intent.putExtra("objectId", news.getObjectId());
                startActivityForResult(comment_intent, Code.NEWSCOMMENTACTIVITY);
            }
        });


        //引用类型
        if(news.getInt("news_type") == News.NEWS_TYPE_REFER)
        {
            news_webview = new WebView(NewsDetailActivity.this);
            //news_webview = new WebView(NewsDetailActivity.this);
            webviewInit(news_webview);
            news_content.addView(news_webview);
            news_loading.setVisibility(View.GONE);
            news_webview.loadUrl(news.getString("news_url"));

            t_webview_back.setVisibility(View.VISIBLE);
            t_webview_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(news_webview.canGoBack())
                    {
                        news_webview.goBack();
                    }
                }
            });

            t_webview_forward.setVisibility(View.VISIBLE);
            t_webview_forward.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(news_webview.canGoForward())
                    {
                        news_webview.goForward();
                    }
                }
            });

            t_imageview_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent share_intent = new Intent(Intent.ACTION_SEND);
                    share_intent.setType("text/plain");
                    share_intent.putExtra(Intent.EXTRA_TEXT, news.getString("news_url"));
                    startActivity(share_intent);
                }
            });


        }
        else if(news.getInt("news_type") == News.NEWS_TYPE_CUSTOM)      //图文新闻
        {
            //t_webview_back.setVisibility(View.GONE);
            //t_webview_forward.setVisibility(View.GONE);
            custom_content = View.inflate(NewsDetailActivity.this, R.layout.news_detail_pixtext_content, null);
            ScrollView content_scrollview = new ScrollView(NewsDetailActivity.this);
            content_scrollview.addView(custom_content);
            news_content.addView(content_scrollview);
            news_loading.setVisibility(View.GONE);
            images_album = (LinearLayout) findViewById(R.id.linearlayout_detail_custom_images);
            t_imageview_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent share_intent = new Intent(Intent.ACTION_SEND);
                    share_intent.setType("text/plain");
                    share_intent.putExtra(Intent.EXTRA_TEXT, news.getString("news_title") + news.getString("news_content"));
                    startActivity(share_intent);
                }
            });

            TextView custom_title = custom_content.findViewById(R.id.textview_detail_custom_title);
            final TextView custom_reporter = custom_content.findViewById(R.id.textview_detail_custom_reporter);
            TextView custom_date = custom_content.findViewById(R.id.textview_detail_custom_date);
            TextView custom_artical = custom_content.findViewById(R.id.textview_detail_custom_artical);


            custom_title.setText(news.getString("news_title"));
            //custom_reporter.setText(news.getString("news_reporter"));
            custom_date.setText(news.getString("news_date"));
            custom_artical.setText(news.getString("news_content"));

            AVObject reporter = news.getAVObject("news_reporter");
            reporter.fetchInBackground(new GetCallback<AVObject>() {
                @Override
                public void done(AVObject avObject, AVException e) {
                    custom_reporter.setText(avObject.getString("user_name"));
                }
            });

            //查询新闻的所有图片
            AVQuery<AVObject> query_news_image = new AVQuery<>("image");
            query_news_image.whereEqualTo("news_id", news);
            query_news_image.include("image_file");
            query_news_image.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> list, AVException e) {
                    if(e == null)
                    {
                        news_image_views = new ArrayList<ImageView>();
                        ImageView tImageView = null;
                        ArrayList<AVFile> t_news_image_files = new ArrayList<>();

                        //按照图片数量建立imageview
                        for(int t = 0; t < list.size(); t ++)
                        {
                            tImageView = new ImageView(NewsDetailActivity.this);
                            tImageView.setImageResource(R.drawable.pic_loading);
                            news_image_views.add(tImageView);
                            images_album.addView(tImageView);
                            //t_news_image_files = list.get(t).getAVFile("image_file");
                            /*
                            t_news_image_files.getDataInBackground(new GetDataCallback() {
                                @Override
                                public void done(byte[] bytes, AVException e) {
                                    //图片下载完成
                                    news_image_views.get(image_set_count).setImageBitmap(
                                            BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
                                    );
                                    image_set_count ++;
                                }
                            });
                            */
                            t_news_image_files.add(list.get(t).getAVFile("image_file"));

                        }

                        //下载图片并显示出来
                        for(int t = 0; t < list.size(); t ++)
                        {
                            t_news_image_files.get(t).getDataInBackground(new GetDataCallback() {
                                @Override
                                public void done(byte[] bytes, AVException e) {
                                    news_image_views.get(image_set_count).setImageBitmap(
                                            BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
                                    );
                                    image_set_count ++;
                                }
                            });
                        }

                    }
                }
            });


        }
        else
        {
            Toast.makeText(NewsDetailActivity.this, "新闻加载失败", Toast.LENGTH_SHORT).show();
        }
    }


    public void onActivityResult(int requestCode,int ResultCode,Intent data) {

        switch (requestCode)
        {
            case Code.NEWSCOMMENTACTIVITY:

                news.fetchInBackground(new GetCallback<AVObject>() {
                    @Override
                    public void done(AVObject avObject, AVException e) {
                        if(e == null)
                        {
                            TextView t_textview_comment = (TextView) findViewById(R.id.textview_news_detail_comment);
                            t_textview_comment.setText(news.getInt("news_comment_count")+"");
                        }
                    }
                });
                break;
        }

    }


}
